package com.yangxk.ureport.provider.sql;

import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SqlProvider implements ReportProvider {

    private SqlOperation sqlOperation;
    private boolean disabled = false;

    private final static String PREFIX = "sql:";
    private final static String NAME = "sql";

    public InputStream loadReport(String file) {
        try {
            if(file.startsWith(PREFIX)){
                file=file.substring(PREFIX.length());
            }

            UReportFileEntity u = sqlOperation.getByName(file);
            ByteArrayInputStream res = new ByteArrayInputStream(u.getContent());
            return res;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void deleteReport(String file) {
        try {
            if(file.startsWith(PREFIX)){
                file=file.substring(PREFIX.length());
            }
            sqlOperation.deleteByName(file);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<ReportFile> getReportFiles() {
        try {
            List<UReportFileEntity> reports = sqlOperation.getList();

            List<ReportFile> res = new ArrayList<ReportFile>(reports.size());
            ReportFile rf = null;
            for (UReportFileEntity report : reports) {
                rf = new ReportFile(report.getName(), report.getUpdateTime());
                res.add(rf);
            }

            return res;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void saveReport(String file, String content) {
        try {
            if(file.startsWith(PREFIX)){
                file=file.substring(PREFIX.length());
            }

            UReportFileEntity report = sqlOperation.getByName(file);
            if (report == null) {
                sqlOperation.saveReport(file, content);
            } else {
                sqlOperation.updateReport(report.getId(), file, content);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public String getName() {
        return NAME;
    }

    public boolean disabled() {
        return disabled;
    }

    public String getPrefix() {
        return PREFIX;
    }

    public void setSqlOperation(SqlOperation sqlOperation) {
        this.sqlOperation = sqlOperation;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }
}
